package belf.migrate.api.util;

import belf.migrate.api.common.TaskLogModel;
import belf.migrate.api.model.LogResult;
import belf.migrate.api.model.ProgressModel;
import belf.migrate.api.taskconf.SyncStatus;
import belf.migrate.api.type.ResultDataType;
import belf.migrate.core.exception.HttpException;
import belf.migrate.core.util.JsonHttp;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 往console发送日志信息
 */
@Slf4j
public class PostLog {

    private static Gson gson = new Gson();
    public void send(String log) {
        String url = EngineConf.getInstance().getString("report.http.endpoint");
        if (null != url) {
            try {
                new JsonHttp().postText(url, log);
            } catch (HttpException e) {
                e.printStackTrace();
            }
        }

    }

    public static void sendLogModel(Long jobId, String eventType, String logMsg, String logLevel, int code, Map<String, Object> progress) {
        String url = EngineConf.getInstance().getString("report.http.endpoint");
        url = url + "/console/taskLog/push";
        try {
            TaskLogModel taskLogModel = new TaskLogModel(
                    eventType,
                    logMsg,
                    logLevel);
            LogResult logResult = new LogResult(jobId, ResultDataType.LOG.getType(), taskLogModel.toJson(), code, gson.toJson(progress));
            log.info("发送log消息：{}， url: {}", logResult.toJson(), url);
            new JsonHttp().postText(url, gson.toJson(logResult));
        } catch (JsonProcessingException | HttpException e) {
            log.error("发送log消息失败！");
        }
    }

    public static void sendSyncStatus(SyncStatus syncStatus){
        String url = EngineConf.getInstance().getString("report.http.endpoint");
        url = url + "/console/syncData/push";
        try{
            log.info("汇报同步状态{}", syncStatus.toJson());
            new JsonHttp().postText(url, gson.toJson(syncStatus));
        }catch (Exception e){
//            log.error("汇报同步状态失败！", e);
            log.error("汇报同步状态失败！");
        }
    }
}
